<!-- 
 * 需求管理
 * @author: 冯宇
 * @since: 2022-05-16
 * index.vue
-->
  <template>
  <div class="user-manage-container h100">
    <router-view v-show="routerCutLevel === 3" class="detailsPage"></router-view>
    <div v-if="routerCutLevel === 2" class="listPage">
      <Filters :formModel="data.formModel" :formLabel="data.formLabel" @reset="resizeForm" @filter="getDemandList"></Filters>
      <TableCom :tableHeader="data.tableHeader" :tableData="data.tableData" @getCurrentChange="getCurrentChange" @getSizeChange="getSizeChange" @comEvent="comEvent" @getSelectChange="getSelectChange" :isShowCheckbox="true" @colSelect="colSelect" @refresh="refreshTable" :pagination="data.pagination" :loading="data.loading" handleWidth="256" :isShowGrooveHandleCol="false" :isShowLogicHandleCol="true">
        <el-button v-for="(item, index) in data.btnList" :key="index" class="tableBtnCss" :style="{ backgroundColor: item.bgColor }" @click="userManageBtnList(index)">
          <svg-icon :name="item.icon" v-if="item.icon"></svg-icon>
          {{ item.name }}
        </el-button>
        <template #handle="scope">
          <div class="table-button">
            <div class="btn" @click="checkRow(scope.row)" style="color: #ffb018" v-if="scope.row.demandState === 'NOT_AUDIT' && scope.row.isConsole === false">审核</div>
            <div class="btn" @click="editRow(scope.row)" :style="{ color: scope.row.valid ? '#D4D4d4' : '#25D390' }" @mouseenter="mouseStatus(scope.row, $event)" v-if="scope.row.isConsole === true || (scope.row.demandState !== 'NOT_AUDIT' && scope.row.demandState !== 'JOIN' && scope.row.demandState === 'JOIN_OK')">编辑</div>
            <div class="btn" @click="operateRow(scope.row, 'del')" style="color: #f74b33">删除</div>
            <label class="btn" v-if="scope.row.demandState !== 'NOT_AUDIT'">
              <div class="text-left">是否启用</div>
              <el-switch v-model="scope.row.valid" @change="operateRow(scope.row, 'valid')" />
            </label>
            <label class="btn" v-if="scope.row.demandState !== 'NOT_AUDIT'">
              <div class="text-left">是否热门</div>
              <el-switch v-model="scope.row.isHot" @change="hotRow(scope.row)" />
            </label>
          </div>
        </template>
      </TableCom>
    </div>

    <!-- 上传文件 -->
    <el-dialog v-model="isShowLead" title="批量导入需求" width="30%" :before-close="() => (isShowLead = false)">
      <uploadDownload @upload="uploadFile" @downloadTemp="downloadFile"></uploadDownload>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, computed, ref } from 'vue'
import { getDemandListApi, operateDemandApi } from '@/api/interface/demand.js'
import { getDictListApi, getDictItemListApi, getRegionApi, getDomainApi } from '@/api/public/publicDict.js'
import{uploadOtherFileApi, dowloadOtherFileApi} from '@/api/public/uploadFile.js'
import { ElMessageBox, ElMessage } from 'element-plus'

import { colFilters, batchHandle, lineHandle, fileDownload } from '@/utils/common.js'
import { useRouter } from 'vue-router'
import { useStore } from 'vuex'
const router = useRouter()
const store = useStore()

const isShowLead = ref(false)

const routerCutLevel = computed(() => {
  return store.getters['setting/routerCutLevel']
})


const data = reactive({
  formModel: {
    needName: '',
    needType: '',
    needAddress: '',
    needField: '',
    investBudget: '',
    date: [],
    valid: '',
    isHot: '',
    isConsole:"",
  },
  formLabel: [
    {
      label: '需求名称',
      model: "needName",
      type: "text",
      width: '160',
      placeholder: '请输入需求名称',
    },
    {
      label: '需求类别',
      model: "needType",
      type: "select",
      width: '160',
      option: [
        {
          key: '全部',
          value: ''
        },
      ],
    },
    {
      label: '需求所在地',
      model: "needAddress",
      type: "select",
      width: '160',
      option: [
        {
          key: '全部',
          value: ''
        },
      ],
    },
    {
      label: '需求所属领域',
      model: "needField",
      type: "select",
      width: '160',
      option: [
        {
          key: '全部',
          value: ''
        },
      ],
    },
    {
      label: '需求投资预算',
      model: "investBudget",
      type: "select",
      width: '160',
      option: [
        {
          key: '全部',
          value: ''
        },
      ],
    },
    {
      label: '是否后台发布',
      model: "isConsole",
      type: "select",
      width: '160',
      option: [
        {
          key: '全部',
          value: ''
        },
        {
          key: '是',
          value: true
        },
        {
          key: '否',
          value: false
        },
      ],
    },
    {
      label: '是否启用',
      model: "valid",
      type: "select",
      width: '160',
      option: [
        {
          key: '全部',
          value: ''
        },
        {
          key: '启用',
          value: true
        },
        {
          key: '禁用',
          value: false
        },
      ],
    },
    {
      label: '是否热门',
      model: "isHot",
      type: "select",
      width: '160',
      option: [
        {
          key: '全部',
          value: ''
        },
        {
          key: '是',
          value: true
        },
        {
          key: '否',
          value: false
        },
      ],
    },
    {
      label: '需求截止时间',
      model: "date",
      type: "dateRange",
      option: [],
    },
  ],
  btnList: [
    {
      name: '新增需求',
      bgColor: '#25D390',
    },
    {
      name: '需求导入',
      bgColor: '#00A2FF',
    },
    {
      name: '批量启用',
      bgColor: '#00A2FF',
    },
    {
      name: '批量禁用',
      bgColor: '#FFB018',
    },
    {
      name: '批量删除',
      bgColor: '#F74B33',
    },
  ],
  tableHeader: [
    {
      label: '需求名称',
      prop: 'demandTitle',
      isLink: true,
      function: 'detail'
    },
    {
      label: '需求类别',
      prop: 'demandTypeName',
    },
    {
      label: '需求所在地',
      prop: 'address',
    },
    {
      label: '所属领域',
      prop: 'industryNameOne',
    },
    {
      label: '投资预算',
      prop: 'demandBudget',
    },
    {
      label: '需求截止时间',
      prop: 'demandExpirationDate',
    },
    {
      label: '需求状态',
      prop: 'demandStateName',
    },
    // {
    //   label: '审核人',
    //   prop: 'demandExpirationDate',
    // },
    // {
    //   label: '申请时间',
    //   prop: 'demandExpirationDate',
    // },
    // {
    //   label: '审核时间',
    //   prop: 'demandExpirationDate',
    // },
  ],
  tableData: [],
  currentSelectList: [],
  pagination: {
    currentPage: 1,
    size: 10,
    total: 0,
  },
  loading: false,
})

//获取需求列表及搜索
const getDemandList = () => {
  data.loading = true
  const params = {
    orderType: 'desc',
    orderField: 'publishDate',
    demandProvinceCode: data.formModel.needAddress,
    // demandCityCode: '',
    // demandAreaCode: '',
    demandBudgetCode: data.formModel.investBudget,
    // demandPublishPerson: '',//需求发布账户
    demandTypeId: data.formModel.needType,
    // id: '',//数据id
    industryCodeOne: data.formModel.needField, //一级技术领域
    ipi: data.pagination.currentPage,
    ips: data.pagination.size,
    isHot: data.formModel.isHot,
    keyword: data.formModel.needName,
    startDate: data.formModel.date ? data.formModel.date[0] : '',
    endDate: data.formModel.date ? data.formModel.date[1] : '',
    valid: data.formModel.valid,
    isConsole: data.formModel.isConsole,
  }
  getDemandListApi(JSON.stringify(params)).then((res) => {
    if (res.status === 200) {
      data.pagination.total = res.data.total
      const arr = res.data.result.map(v => {
        v.address = v.demandProvinceName + v.demandCityName + v.demandAreaName
        return v
      })
      data.loading = false
      data.tableData = arr
    }
  })
}
getDemandList()
//重置搜索条件
const resizeForm = () => {
  for (let key in data.formModel) {
    if (typeof data.formModel[key] == 'string') {
      data.formModel[key] = ''
    } else {
      data.formModel[key] = []
    }
  }
  getDemandList()
}



//需求类别、需求预算下拉框
const getNeedTypeSelectList = async () => {
  const dict = {
    ipi: 1,
    ips: 20,
    keyName: '',
  }
  const arr = await getDictListApi(dict).then((res) => {
    if (res.status === 200) {
      return res.data.result
    }
  })
  arr.forEach((v) => {
    if (v.keyId == 'DICT_DEMAND') {
      let needTypeDict = {
        dictType: v.keyId,
      }
      getDictItemListApi(needTypeDict).then((res) => {
        if (res.status === 200) {
          if (res.status === 200) {
            let arr = res.data.result.map(v => ({
              key: v.keyName,
              value: v.keyId
            }))

            for (let v of data.formLabel) {
              if (v.model == 'needType') {
                v.option = [...v.option, ...arr]
                break
              }
            }
          }
        }
      })
    } else if (v.keyId == 'DICT_BUDGET') {
      let budgetDict = {
        dictType: v.keyId,
      }
      getDictItemListApi(budgetDict).then((res) => {
        if (res.status === 200) {
          let arr = res.data.result.map(v => ({
            key: v.keyName,
            value: v.keyId
          }))
          for (let v of data.formLabel) {
            if (v.model == 'investBudget') {
              v.option = [...v.option, ...arr]
              break
            }
          }
        }
      })
    }
  })
}
getNeedTypeSelectList()
//获取省级行政区数据
const getRegion = () => {
  getRegionApi({ criSuperiorCode: '000000' }).then((res) => {
    if (res.status === 200) {
      let arr = res.data.map(v => ({
        key: v.criName,
        value: v.criCode
      }))
      for (let v of data.formLabel) {
        if (v.model == 'needAddress') {
          v.option = [...v.option, ...arr]
          break
        }
      }
    }
  })
}
getRegion()
//获取需求领域
const getDomain = () => {
  getDomainApi({ parentId: 0 }).then((res) => {
    if (res.status === 200) {
      let arr = res.data.map(v => ({
        key: v.keyName,
        value: v.keyId
      }))
      for (let v of data.formLabel) {
        if (v.model == 'needField') {
          v.option = [...v.option, ...arr]
          break
        }
      }
    }
  })
}
getDomain()




//列筛选
const colSelect = (headerArr, type, e, currentItem) => {
  if (type === 'filter') {
    const currentData = colFilters(headerArr, e, currentItem, data.tableHeader)
    data.tableHeader = currentData
  } else {
    //全选/全取消
    data.tableHeader = headerArr
  }
}
//刷新
const refreshTable = () => {
  getDemandList()
}
//表头功能
const userManageBtnList = (index) => {
  switch (index) {
    case 0:
      router.push({ name: 'AddNeed' })
      break
    case 1:
      isShowLead.value = true
      break
    case 2:
      const startArr = data.currentSelectList.map(v => v.id)
      const startFunction = () => {
        const start = {
          batchType: "START",
          ids: startArr,
        }
        operateDemandApi(JSON.stringify(start)).then(res => {
          if (res.status === 200) {
            ElMessage({
              message: res.message,
              type: 'success',
            })
            getDemandList()
          }
        })
      }
      batchHandle(startArr, 'START', startFunction)
      break
    case 3:
      const stopArr = data.currentSelectList.map(v => v.id)
      const stopFunction = () => {
        const stop = {
          batchType: "STOP",
          ids: stopArr
        }
        operateDemandApi(JSON.stringify(stop)).then(res => {
          if (res.status === 200) {
            ElMessage({
              message: res.message,
              type: 'success',
            })
            getDemandList()
          }
        })
      }
      batchHandle(stopArr, 'STOP', stopFunction)
      break
    case 4:
      const delArr = data.currentSelectList.map(v => v.id)
      const delFunction = () => {
        const del = {
          batchType: "DEL",
          ids: delArr
        }
        operateDemandApi(JSON.stringify(del)).then(res => {
          if (res.status === 200) {
            ElMessage({
              message: res.message,
              type: 'success',
            })
            getDemandList()
          }
        })
      }
      batchHandle(delArr, 'DEL', delFunction)
      break
    default:
      break
  }
}
//勾选需求
const getSelectChange = (row) => {
  data.currentSelectList = row
}
//分页查看
const getCurrentChange = (cur) => {
  data.pagination.currentPage = cur
  getDemandList()
}
//每页条数
const getSizeChange = (cur) => {
  data.pagination.size = cur
  getDemandList()
}


//上传文件
const uploadFile = (data) => {
  let fd = new FormData()
  fd.append('file', data.file);
  fd.append('dataType', 'DEMAND')
  uploadOtherFileApi(fd).then(res => {
    isShowLead.value = false
    ElMessage.success(res.message)
    getDemandList()
  })
}
//下载文件
const downloadFile = () => {
  dowloadOtherFileApi({ dataType: 'DEMAND' }).then(res => {
    console.log(res);
    fileDownload({
      fileSuffix: 'xlsx',
      name:'技术需求导入模板'
    }, res)
  })
}


//详情
const comEvent = (type, row) => {
  sessionStorage.demandId = row.id
  if (type == 'detail') {
    router.push({ name: 'NeedDetail', params: { id: row.id, type: "detail" } })
  }
}
//审核
const checkRow = (row) => {
  sessionStorage.demandId = row.id
  router.push({ name: 'CheckNeed', params: { id: row.id, type: 'check' } })
}
//编辑需求
const editRow = (row) => {
  sessionStorage.demandId = row.id
  if (row.valid) {
    return
  } else {
    router.push({ name: 'EditNeed', params: { id: row.id } })
  }
}
//单个删除启用禁用
const operateRow = (row, type) => {
  if (type == 'del') {
    const delFunction = () => {
      let params = {
        batchType: 'DEL',
        ids: [row.id],
      }
      operateDemandApi(JSON.stringify(params)).then((res) => {
        if (res.status === 200) {
          ElMessage({
            message: res.message,
            type: 'success',
          })
          getDemandList()
        }
      })
    }
    lineHandle(row, 'del', delFunction)
  } else if (type == 'valid') {
    const validFunction = () => {
      let params = {
        batchType: row.valid ? 'STOP' : 'START',
        ids: [row.id],
      }
      operateDemandApi(JSON.stringify(params)).then((res) => {
        if (res.status === 200) {
          ElMessage({
            message: res.message,
            type: 'success',
          })
          row.valid = !row.valid
        }
      })
    }
    lineHandle(row, 'valid', validFunction)
  }
}
//热门
const hotRow = (row) => {
  const hotFunction = () => {
    const params = {
      batchType: row.isHot ? 'STOP_HOT' : "START_HOT",
      ids: [row.id],
    }
    operateDemandApi(JSON.stringify(params)).then((res) => {
      if (res.status === 200) {
        ElMessage({
          message: res.message,
          type: 'success',
        })
        row.isHot = !row.isHot
      }
    })
  }
  lineHandle(row, 'isHot', hotFunction)
}
//行内编辑鼠标手型
const mouseStatus = (row, e) => {
  if (row.valid) {
    e.target.style.cursor = 'not-allowed'
  } else {
    e.target.style.cursor = 'pointer'
  }
}
</script>

<style lang="scss" scoped>
.table-button {
  display: flex;
  justify-content: flex-start;

  .btn {
    display: flex;
    align-items: center;
    cursor: pointer;
    margin-right: 10px;

    .text-left {
      margin-right: 2px;
    }
  }

  .btn:last-child {
    margin-right: 0;
  }
}
</style>